﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;

namespace RESP_IIWaterAssessment
{
    public partial class MineralizationFormReport : Form
    {
        public MineralizationFormReport()
        {
            InitializeComponent();
        }

        int regID, avpID, year, month;

        private void MineralizationFormReport_Load(object sender, EventArgs e)
        {
            cbRegion.SelectedIndexChanged -= cbRegion_SelectedIndexChanged;
            cbRegion.DataSource = UtilClass.FillCBRegions();
            cbRegion.DisplayMember = "Name";
            cbRegion.ValueMember = "ID";

            if (InformationClass.isAdmin)
            {
                cbRegion.SelectedIndex = -1;
                cbRegion.Text = string.Empty;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
            }
            else
            {
                chbRegion.Checked = true;
                cbRegion.Enabled = chbRegion.Enabled = false;
                regID = InformationClass.regionID;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
                cbRegion.SelectedValue = regID;
                cbRegion_SelectedIndexChanged(cbRegion, null);
                cbAVP.Enabled = true;
                cbAVP.Text = string.Empty;
                //toolStrip1.Visible = false;
            }

            string[] month;
            if (InformationClass.Lang)
                month = new string[] { "1 Апреля", "1 Июля", "1 Октября" };
            else
                month = new string[] { "1 Апрел", "1 Июл", "1 Октябр" };

            for (int i = 1; i <= month.Length; i++)
            {
                var m = new
                {
                    ID = i,
                    Name = month[i - 1]
                };
                cbMonth.Items.Add(m);
            }
            cbMonth.DisplayMember = "Name";
            cbMonth.ValueMember = "ID";

            for (int i = 1991; i < 2100; i++)
            {
                cbYear.Items.Add(i);
            }

            cbYear.SelectedIndex = cbYear.FindStringExact(DateTime.Now.Year.ToString());
            this.year = Convert.ToInt32(cbYear.Text);
        }

        private void cbRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbRegion.SelectedIndex == -1)
                return;

            regID = Convert.ToInt32(cbRegion.SelectedValue);
            cbAVP.SelectedIndexChanged -= cbAVP_SelectedIndexChanged;
            cbAVP.DataSource = UtilClass.FillAVP(regID);
            cbAVP.ValueMember = "ID";
            cbAVP.DisplayMember = "Name";
            cbAVP.SelectedIndex = -1;
            cbAVP.Text = string.Empty;
            cbAVP.SelectedIndexChanged += new EventHandler(cbAVP_SelectedIndexChanged);
            cbAVP.Enabled = true;
        }

        private void cbAVP_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbAVP.SelectedIndex >= 0)
            {
                avpID = Convert.ToInt32(cbAVP.SelectedValue);
            }
        }

        private void cbYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbYear.SelectedIndex >= 0)
            {
                year = Convert.ToInt32(cbYear.Text);
            }
            else
                year = 0;
        }

        private void cbMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbMonth.SelectedIndex >= 0)
            {
                month = cbMonth.SelectedIndex + 1;
            }
            else
                month = 0;
        }

        private void chbRegion_CheckedChanged(object sender, EventArgs e)
        {
            cbRegion.Enabled = chbRegion.Checked;
        }

        private void chbAVP_CheckedChanged(object sender, EventArgs e)
        {
            cbAVP.Enabled = chbAVP.Checked;
        }

        private void chbYear_CheckedChanged(object sender, EventArgs e)
        {
            cbYear.Enabled = chbYear.Checked;
            if (!chbYear.Checked)
                chbPeriod.Checked = false;
        }

        private void chbPeriod_CheckedChanged(object sender, EventArgs e)
        {
            if (chbYear.Checked)
                cbMonth.Enabled = chbPeriod.Checked;
            else
                chbPeriod.Checked = cbMonth.Enabled = false;
        }

        private void buttonShow_Click(object sender, EventArgs e)
        {
            int? rId, aId, y;
            DateTime? dt;
            if (chbPeriod.Checked)
            {
                switch (month)
                {
                    case 1:
                        dt = new DateTime(year, 4, 1);
                        break;
                    case 2:
                        dt = new DateTime(year, 7, 1);
                        break;
                    case 3:
                        dt = new DateTime(year, 10, 1);
                        break;
                    default:
                        dt = null;
                        break;
                }
            }
            else
                dt = null;


            if (chbRegion.Checked && regID > 0)
                rId = regID;
            else
                rId = null;

            if (chbAVP.Checked && avpID > 0)
                aId = avpID;
            else
                aId = null;

            if (chbYear.Checked && year > 0)
                y = year;
            else
                y = null;

            dgvReport.DataSource = DBClass.RESPContext.MineralizationReport(rId, aId, dt, y);

            if (InformationClass.Lang)
            {
                dgvReport.Columns["AVP"].HeaderText = "АВП";
                dgvReport.Columns["Area"].HeaderText = "Пл.орошаемых земель";
                dgvReport.Columns["MinYear"].HeaderText = "Год";
                dgvReport.Columns["AreaObserved"].HeaderText = "Пл.охвачен. наблюдением";
                dgvReport.Columns["GW01"].HeaderText = "Глубина залегания ГВ 0-1";
                dgvReport.Columns["GW12"].HeaderText = "Глубина залегания ГВ 1-2";
                dgvReport.Columns["GW23"].HeaderText = "Глубина залегания ГВ 2-3";
                dgvReport.Columns["GW35"].HeaderText = "Глубина залегания ГВ 3-5";
                dgvReport.Columns["GW5"].HeaderText = "Глубина залегания ГВ >5";
                dgvReport.Columns["UGV2"].HeaderText = "Пл-дь залег. УГВ до 2м";
                dgvReport.Columns["SGW01"].HeaderText = "Глубина залегания MГВ 0-1";
                dgvReport.Columns["SGW13"].HeaderText = "Глубина залегания MГВ 1-3";
                dgvReport.Columns["SGW35"].HeaderText = "Глубина залегания MГВ 3-5";
                dgvReport.Columns["SGW510"].HeaderText = "Глубина залегания MГВ 5-10";
                dgvReport.Columns["SGW10"].HeaderText = "Глубина залегания MГВ >10";

                dgvReport.Columns["MGV3"].HeaderText = "Пл-дь МГВ, >3г/л";

                dgvReport.Columns["low"].HeaderText = "Степень засоления слабое";
                dgvReport.Columns["average"].HeaderText = "Степень засоления среднее";
                dgvReport.Columns["high"].HeaderText = "Степень засоления сильное";
            }
            else
            {
                dgvReport.Columns["AVP"].HeaderText = "СИУ номи";
                dgvReport.Columns["Area"].HeaderText = "Майдон, минг га.";
                dgvReport.Columns["MinYear"].HeaderText = "йил";
                dgvReport.Columns["AreaObserved"].HeaderText = "Кузатув олиб бориладиган ерлар (нетто)";
                dgvReport.Columns["GW01"].HeaderText = "Жумладан, ер ости сувлари жойлашиш чуқурлиги (м) 0-1";
                dgvReport.Columns["GW12"].HeaderText = "Жумладан, ер ости сувлари жойлашиш чуқурлиги (м) 1-2";
                dgvReport.Columns["GW23"].HeaderText = "Жумладан, ер ости сувлари жойлашиш чуқурлиги (м) 2-3";
                dgvReport.Columns["GW35"].HeaderText = "Жумладан, ер ости сувлари жойлашиш чуқурлиги (м) 3-5";
                dgvReport.Columns["GW5"].HeaderText = "Жумладан, ер ости сувлари жойлашиш чуқурлиги (м) >5";
                dgvReport.Columns["UGV2"].HeaderText = "Пл-дь залег. УГВ до 2м";
                dgvReport.Columns["SGW01"].HeaderText = "Жумладан, ер ости сувлари минераллашуви (г/л) 0-1";
                dgvReport.Columns["SGW13"].HeaderText = "Жумладан, ер ости сувлари минераллашуви (г/л) 1-3";
                dgvReport.Columns["SGW35"].HeaderText = "Жумладан, ер ости сувлари минераллашуви (г/л) 3-5";
                dgvReport.Columns["SGW510"].HeaderText = "Жумладан, ер ости сувлари минераллашуви (г/л) 5-10";
                dgvReport.Columns["SGW10"].HeaderText = "Жумладан, ер ости сувлари минераллашуви (г/л) >10";

                dgvReport.Columns["MGV3"].HeaderText = "Ер ости сувлари минерал-лашиши  <3г/л бўлган майдон-лар";

                dgvReport.Columns["low"].HeaderText = "Тупроқ шўрланиши кам";
                dgvReport.Columns["average"].HeaderText = "Тупроқ шўрланиши ўрта";
                dgvReport.Columns["high"].HeaderText = "Тупроқ шўрланиши кучли";
            }

            for (int i = 0; i < dgvReport.RowCount; i++)
            {
                dgvReport.Rows[i].HeaderCell.Value = (i + 1).ToString();
            }
        }

        private void buttonExcel_Click(object sender, EventArgs e)
        {
            if (dgvReport.RowCount > 0)
            {
                MessageBox.Show(msgClass.msgWaiting);
                GetReport();
                excelworksheet.Select(1);
                excelapp.Visible = true;
            }
        }

        Sheets excelsheets;
        Worksheet excelworksheet;
        Microsoft.Office.Interop.Excel.Application excelapp;
        Workbook excelappworkbook;

        private void GetReport()
        {
            excelapp = new Microsoft.Office.Interop.Excel.Application();

            if (InformationClass.Lang)
                excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\i10r12.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            else
                excelapp.Workbooks.Open(System.Windows.Forms.Application.StartupPath + @"\Templates\i10r12uz.xls", false, true, Type.Missing, Type.Missing, Type.Missing, true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            excelappworkbook = excelapp.Workbooks[1];
            excelsheets = excelappworkbook.Worksheets;// .Worksheets[0]; //Sheets 
            excelworksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelsheets.get_Item(1);

            excelworksheet.Cells.NumberFormat = "@";

            if (chbRegion.Checked)
                excelworksheet.Cells[4, 3] = cbRegion.Text;

            string str = "Период: ";

            if (chbPeriod.Checked)
                str += cbMonth.Text;

            if (chbYear.Checked)
                str += " " + cbYear.Text + " года";

            excelworksheet.Cells[6, 2] = str;

            for (int i = 0; i < dgvReport.Rows.Count; i++)
            {
                int k = 3;
                for (int j = 0; j < dgvReport.Columns.Count; j++)
                {
                    if (dgvReport.Columns[j].Name == "MinYear")
                    {
                        k--;
                        continue;
                    }
                    excelworksheet.Cells[i + 10, dgvReport.Columns[j].DisplayIndex + k] = dgvReport[j, i].FormattedValue;
                    addBorder(excelworksheet.Cells[i + 10, dgvReport.Columns[j].DisplayIndex + k]);
                }
                excelworksheet.Cells[i + 10, 2] = i + 1;
                addBorder(excelworksheet.Cells[i + 10, 2]);
            }

            excelworksheet.Columns.AutoFit();
            excelworksheet.Rows.AutoFit();
        }

        private void addBorder(object p)
        {
            Range tmpRange = excelworksheet.get_Range(p, p);
            tmpRange.Borders[XlBordersIndex.xlEdgeLeft].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeBottom].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeRight].LineStyle = XlLineStyle.xlContinuous;
            tmpRange.Borders[XlBordersIndex.xlEdgeTop].LineStyle = XlLineStyle.xlContinuous;
        }

        private void dgvReport_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (dgvReport.Columns.Count > 0)
            {
                if (!e.ColumnIndex.Equals(dgvReport.Columns["AVP"].Index) &&
                    !e.ColumnIndex.Equals(dgvReport.Columns["MinYear"].Index))
                {
                    e.Value = ((decimal)e.Value).ToString("N2");
                }
            }
        }

        private void buttonPrint_Click(object sender, EventArgs e)
        {
            if (dgvReport.RowCount > 0)
                PrintDGV.Print_DataGridView(dgvReport);
        }
    }
}
